var canvas = document.getElementById( "canvas" );
var canvasContainer = document.getElementById( "canvasContainer" );

var scrollTarget;

var scroll = function(instant) {
	var targetX = Math.round( scrollTarget.cx.baseVal.value - canvasContainer.offsetWidth / 2  );
	var targetY = Math.round( scrollTarget.cy.baseVal.value - canvasContainer.offsetWidth / 2  );
	
	var moveX = targetX - canvasContainer.scrollLeft;
	var moveY = targetY - canvasContainer.scrollTop;
	if( !instant && Math.abs( moveX ) > 5 ) {
		moveX = moveX / 4;
	}
	if( !instant && Math.abs( moveY ) > 5 ) {
		moveY = moveY / 4;
	}
	if( moveX == 0 && moveY == 0 ) {
		scrollTarget = null;
   	    return;	
	}
	 
	canvasContainer.scrollTop = canvasContainer.scrollTop + moveY;
	canvasContainer.scrollLeft = canvasContainer.scrollLeft + moveX;
	
	setTimeout( scroll, 20 );	 
	
}

var render = function(r, node){
    /* the default node drawing */
	if( node.size == undefined || node.size < 1 ) {
		node.size = 1;
	}
    var color = "hsb(" + (node.color / 16) +", "+(1 - 0.9 / node.size)+", 0.8  )";
    var size = 1;
    var ellipse = r.ellipse(0, 0, 15 + size * 15, 10 + size * 10).attr({
        fill: color,
        stroke: color,
        "stroke-width": 2
    });
    /* set DOM node ID */
    ellipse.node.id = node.label || node.id;
	var text = r.text(0, 30, node.label || node.id);
	text.node.id = "textid-"+ ( node.label || node.id );
    shape = r.set().push(ellipse).push( text );
    ellipse.node.onclick = function(){
        scrollTarget = this;
    	setTimeout( scroll, 20 );	 
    }
	text.node.onclick = function() {
		window.location = node.id.replace( "textid-", "");
	};
    return shape;
}



Math.seedrandom( "random" );

var width = document.defaultView.getComputedStyle(canvas,"").getPropertyValue("width").replace( "px", "" );
var height = document.defaultView.getComputedStyle(canvas,"").getPropertyValue("height").replace( "px", "" );
var width = canvas.offsetWidth;
var height = canvas.offsetHeight;
var g = new Graph();

${nodeDefs}

${edgeDefs}

var layouter = new Graph.Layout.Spring(g);
var renderer = new Graph.Renderer.Raphael('canvas', g, width, height);

scrollTarget = document.getElementById( "${origin}" );
scroll( true );
